package daohibernate;

import hibernate.HibernateUtil;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import negocio.beans.central.Proveedor;
import negocio.beans.central.Stock;
import negocio.beans.oficinaventa.Rodamiento;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class StockDAO {
	private static StockDAO instancia = null;
	private static SessionFactory sf = null;	
	
	public static StockDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new StockDAO();
		} 
		return instancia;
	}	
	
	public Stock buscarStockPorCodigoRodamiento(int codigo)
	{
		Session s = sf.openSession();
		
		List<Stock> r  = s.createQuery("from Stock where rodamiento = " + codigo).list();
		
		s.close();
		
		for(Stock p : r){
			return p;
		}
		
		return null;
	}

	public Set<Stock> obtenerStock(){
		Session s = sf.openSession();

		@SuppressWarnings("unchecked")
		Iterator<Object> lista = s.createQuery("from Stock s join s.rodamiento").iterate();
		Set<Stock> resultado = new HashSet<Stock>();
		
		
		while(lista.hasNext()){
			Object[] tupla = (Object[]) lista.next();
			
			Stock stock = (Stock)tupla[0];
			Rodamiento r = (Rodamiento)tupla[1];
			stock.setRodamiento(r);
			resultado.add(stock);
			
		}
		s.close();
		
		return resultado;

	}	
	
	public void altaStock(Stock stock)
	{
		Session s = sf.openSession();
		s.beginTransaction();
		
		s.persist(stock);
		
		s.flush();
		s.getTransaction().commit();
	}
	
	public void modificarStock(String codigoEstandar, int cantidad){
		Session s = sf.openSession();

		@SuppressWarnings("unchecked")
		Iterator<Object> lista = s.createQuery("from Stock s join s.rodamiento r where r.codigoEstandar = '" + codigoEstandar + "'").iterate();
		
		
		while(lista.hasNext()){
			Object[] tupla = (Object[]) lista.next();
			
			Stock stock = (Stock)tupla[0];
			Rodamiento r = (Rodamiento)tupla[1];
			stock.setRodamiento(r);
			stock.setCantidadInterna(cantidad);
			
			s.beginTransaction();
			
			s.update(stock);
			
			s.flush();
			s.getTransaction().commit();
			
		}
		s.close();		
		
	}
	
	public void modificarStock(Stock stock){
		Session s = sf.openSession();
		s.beginTransaction();
				
		s.update(stock);
		
		s.flush();
		
		s.getTransaction().commit();
		s.close();	
		
	}
	
	public void bajaStock(Stock stock){
		Session s = sf.openSession();
		s.beginTransaction();
				
		s.delete(stock);
		
		s.flush();
		
		s.getTransaction().commit();
		s.close();	
		
	}

}
